from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import os
import logging

from config.config_manager import get_app_config
from api.his_drug_api import router as his_drug_router
from core.logger import init_logger
from task.scheduler import start_scheduler, stop_scheduler
from static.swagger_docs import add_offline_swagger_docs
from core.db_manager import db_manager

init_logger()
logger = logging.getLogger(__name__)

# --- 应用生命周期事件 ---
@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # --- 启动事件 ---
    print("服务启动中...")
    
    # 初始化数据库连接
    db_manager.initialize()

    # 启动定时任务
    start_scheduler()
    print("定时任务已启动")
    
    yield
    
    # --- 关闭事件 ---
    print("服务关闭中...")
    stop_scheduler()
    print("定时任务已关闭")

# --- FastAPI 应用实例 ---
app_config = get_app_config()
app_config.update({
    "docs_url": None,  # 禁用默认的 /docs 路由
    "redoc_url": None,  # 禁用默认的 /redoc 路由
    "openapi_url": None,  # 禁用默认的 /openapi.json 路由
})
app = FastAPI(
    lifespan=lifespan,
    **app_config
)

# 静态文件配置 - 直接写死配置
static_dir = "static"
if not os.path.exists(static_dir):
    os.makedirs(static_dir)

app.mount("/static", StaticFiles(directory=static_dir), name="static")

# 注册所有路由
app.include_router(his_drug_router)

# 添加根路径健康检查
@app.get("/health")
async def health_check():
    """根路径健康检查"""
    return {"status": "healthy", "message": "服务运行正常"}

@app.get("/")
async def root():
    """根路径"""
    return {"message": "HIS 适配服务", "docs": "/docs"}

# 添加离线 Swagger 文档
add_offline_swagger_docs(app)

@app.get("/openapi.json", include_in_schema=False)
async def openapi():
    """生成 OpenAPI 规范"""
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title=app.title,
        version=app.version,
        description=app.description,
        routes=app.routes,
    )
    app.openapi_schema = openapi_schema
    return app.openapi_schema